package football.modele;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

@Entity
public class Match implements Serializable, java.lang.Comparable {

	private static final long serialVersionUID = -5613277162025930016L;
	private int idMatch;
	private Phase phase;
	private Equipe equipeA;
	private Equipe equipeB;
	private Set<But> listeButs;
	private Arbitre arbitre;
	private boolean matchTermine = false;

	public Match() {
		super();
		this.listeButs = new HashSet<But>();
	}

	public Match(Phase phase, Equipe equipeA, Equipe equipeB, Arbitre arbitre) {
		super();
		this.phase = phase;
		this.equipeA = equipeA;
		this.equipeB = equipeB;
		this.arbitre = arbitre;
		this.listeButs = new HashSet<But>();
	}

	@Id
	@GeneratedValue
	public int getIdMatch() {
		return idMatch;
	}

	public void setIdMatch(int idMatch) {
		this.idMatch = idMatch;
	}

	@OneToOne
	public Equipe getEquipeA() {
		return equipeA;
	}

	public void setEquipeA(Equipe equipeA) {
		this.equipeA = equipeA;
	}

	@OneToOne
	public Equipe getEquipeB() {
		return equipeB;
	}

	public void setEquipeB(Equipe equipeB) {
		this.equipeB = equipeB;
	}

	@OneToMany(mappedBy = "match", cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
	public Set<But> getListeButs() {
		return listeButs;
	}

	public void setListeButs(Set<But> listeButs) {
		this.listeButs = listeButs;
	}

	@OneToOne
	public Arbitre getArbitre() {
		return arbitre;
	}

	public void setArbitre(Arbitre arbitre) {
		this.arbitre = arbitre;
	}

	@ManyToOne
	public Phase getPhase() {
		return phase;
	}

	public void setPhase(Phase phase) {
		this.phase = phase;
	}

	public Equipe vainqueurMatch() {
		if (scoreA() > scoreB())
			return equipeA;
		else
			return equipeB;
	}

	public int scoreA() {
		int i = 0;
		for (But b : listeButs) {
			if (b.getEquipe().getIdEquipe() == equipeA.getIdEquipe()) {
				i++;
			}
		}
		return i;
	}

	public int scoreB() {
		int i = 0;
		for (But b : listeButs) {
			if (b.getEquipe().getIdEquipe() == equipeB.getIdEquipe()) {
				i++;
			}
		}
		return i;
	}

	public boolean isMatchTermine() {
		return matchTermine;
	}

	public void setMatchTermine(boolean matchTermine) {
		this.matchTermine = matchTermine;
	}

	public boolean matchNul() {
		return scoreA() == scoreB();
	}

	@Override
	public int compareTo(Object o) {
		int nombre1 = ((Match) o).getIdMatch();
		int nombre2 = this.getIdMatch();
		if (nombre1 > nombre2)
			return -1;
		else if (nombre1 == nombre2)
			return 0;
		else
			return 1;
	}

}
